package cc.wanforme.st.server.rw;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;

import cc.wanforme.st.server.util.SimpleJackson;

public class Remap {

	public static void main(String[] args) throws IOException {
		File fontFile = new File("C:\\Users\\Administrator\\Downloads\\otfcc-win64-0.10.4\\siyuan.json");
		File targetFile = new File("C:\\Users\\Administrator\\Downloads\\otfcc-win64-0.10.4\\siyuan-mix.json");

		byte[] bs = Files.readAllBytes(fontFile.toPath());
		// 读取并打乱映射关系
		String newJson = reMap(new String(bs));
		// 保存打乱的关系
		Files.write(targetFile.toPath(), newJson.getBytes());
		System.out.println("end");
	}

	/** 读取映射关系，并打乱映射关系 */
	public static String reMap(String jsonStr) throws JsonMappingException, JsonProcessingException {
		// 读取映射关系
		TypeReference<HashMap<String, Object>> typeReference = new TypeReference<HashMap<String, Object>>() {
		};
		HashMap<String, Object> font = SimpleJackson.toAny(jsonStr, typeReference);

		@SuppressWarnings("unchecked")
		Map<String, String> cmap = (Map<String, String>) font.get("cmap");

		// 打乱键值映射
		Map<String, String> mixedMap = mixMap(cmap);

		// 重新转换成 json
		font.put("cmap", mixedMap);

		String json = SimpleJackson.toJsonString(font);
		return json;
	}
	
	/** 打乱 map 的映射关系 */
	private static Map<String, String> mixMap(Map<String, String> oldMap) {
		List<String> keys = new ArrayList<>(oldMap.keySet());
		List<String> values = new ArrayList<>(oldMap.values());

		Random keyRan = new Random();
		Random valueRan = new Random();

		Map<String, String> map = new HashMap<>();
		while (!keys.isEmpty()) {
			int nextKey = keyRan.nextInt(keys.size());
			int nextVal = valueRan.nextInt(values.size());

			String key = keys.remove(nextKey);
			String val = values.remove(nextVal);

			// System.out.println("keys:" + keys.size() + ", values:" + values.size());
			map.put(key, val);
		}

		return map;
	}

	
}
